import os, django
import time
from bs4 import BeautifulSoup
from selenium import webdriver

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "get_weather.settings")  # project_name 项目名称
django.setup()
from API_getWeather.models import cityCodes


class getCityCode:
    def __init__(self):
        option = webdriver.ChromeOptions()
        option.add_argument("--headless")
        option.add_argument("--disable-gpu")
        option.add_argument("--start-maximized")
        option.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
        global driver
        driver = webdriver.Chrome(options=option)
        driver.get('https://www.tceic.com/9j67h1764g7302768l99390k.html')

    def start(self):
        contents = driver.page_source
        soup = BeautifulSoup(contents, 'lxml')  # 将页面内容解析出来
        result = soup.find_all('p')[0]  # 取p标签下的所有内容
        dataList = [i for i in result]
        newList = dataList[1::2]  # 去除<br/>,下标从1开始步长为2
        nowList = [x.strip() for x in newList if x.strip() != '']  # 去除换行符\n
        global dictData
        dictData = {}
        for x in nowList:
            dictData[x[10:]] = x[:9]
        return dictData

    def __del__(self):
        cityCodes(all_code=dictData).save()  # 保存数据
        driver.quit()



if __name__ == '__main__':
    t = getCityCode().start()
    print(t['郫县'])
